import $http from "@/http/index";

// 接口返回数据结构
export interface IResponse {
  code: number;
  message: string;
  data?: any;
}

// 配置项
const DEBOUNCE_WAIT: number = 300;

/**
 * 带防抖的 HTTP 请求函数
 * @param method 请求方法
 * @param url  请求地址
 * @param config 请求配置
 */
export const debouncedHttpRequest = debounce(async (method: 'get' | 'post' | 'json', url: string, config?: any): Promise<IResponse> => {
  return await httpRequest(method, url, config);
}, DEBOUNCE_WAIT);

/**
 * HTTP 请求函数
 * @param method 请求方法
 * @param url  请求地址
 * @param data 请求数据
 */
async function httpRequest(method: 'post' | 'json' | 'get', url: string, data?: any): Promise<IResponse> {
  try {
    if (method.toLocaleLowerCase() === 'get') {
      return await $http.get(url, { params: data });
    } else if (method.toLocaleLowerCase() === 'post') {
      return await $http.post(url, data,{headers: {'Content-Type': 'application/x-www-form-urlencoded'}});
    } else if (method.toLocaleLowerCase() === 'json') {
      return await $http.post(url, data, {headers: {'Content-Type': 'application/json'}});
    }
    return { code: -1, message: `${method} Unsupported HTTP method`, data: null };
  } catch (error: any) {
    console.error('httpRequest error:', error); // 添加日志
    throw error; // 重新抛出异常以便调用方处理
  }
}

// 防抖函数
function debounce<T>(func: (this: T, ...args: any[]) => Promise<IResponse>, wait?: number) {
  let timeout: number | null = null;
  let resolve: (value: IResponse | PromiseLike<IResponse>) => void;
  let reject: (reason?: any) => void;
  let promise: Promise<IResponse>;

  return function (this: T, ...args: any[]) {
    if (timeout !== null) clearTimeout(timeout);

    promise = new Promise((res, rej) => {
      resolve = res;
      reject = rej;
    });

    timeout = setTimeout(async () => {
      try {
        const result = await func.apply(this, args);
        resolve(result);
      } catch (error) {
        reject(error);
      }
    }, wait || DEBOUNCE_WAIT);

    return promise;
  };
}


